﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;

namespace System.Web.UI
{
    public delegate void PageEvent(object sender, System.EventArgs e);
    public class Page : IHttpHandler
    {
        public bool IsReusable{get{ return false; } }
        public HttpContext Context { get; set; }
        public event PageEvent page_Load_Event;
        public static bool IsInit = false;

        static IntPtr functionPtr = IntPtr.Zero;
        public Page()
        {
            //Init();
        }

        /// <summary>
        /// 自动绑定事件
        /// </summary>
        public void Init()
        {
            if (!IsInit)
            {
                IsInit = true;
                Type handlerType = this.GetType();
                MethodInfo pageLoadMethodInfo = handlerType.GetMethod("Page_Load", BindingFlags.NonPublic | BindingFlags.Instance);
                ConstructorInfo pageEventConstructor = typeof(System.Web.UI.PageEvent).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) });
                MethodInfo add_page_Load_EventMethodInfo = null;
                bool hasPageLoadMethod = false;
                if (pageLoadMethodInfo != null)
                {
                    EventInfo page_Load_Event = typeof(System.Web.UI.Page).GetEvent("page_Load_Event");
                    add_page_Load_EventMethodInfo = page_Load_Event.GetAddMethod();
                    ParameterInfo[] parameters = pageLoadMethodInfo.GetParameters();
                    if (parameters.Length == 2)
                    {
                        if (parameters[0].ParameterType == typeof(object)
                            && parameters[1].ParameterType == typeof(System.EventArgs)
                            )
                        {
                            hasPageLoadMethod = true;
                            functionPtr = pageLoadMethodInfo.MethodHandle.GetFunctionPointer();
                        }
                    }
                }
            }
            if (functionPtr!=IntPtr.Zero)
            {
                page_Load_Event += new PageEvent((sender,e)=> {
                    PageEvent dele= FastDelegateCreator<PageEvent>.BindTo(this, functionPtr);
                    dele(sender, e);
                });
                //IntPtr method=MethodInfo.GetMethodFromHandle()
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            this.Context = context;
            if (page_Load_Event != null)
            {
                page_Load_Event(context, new EventArgs());
            }
        }
    }
}
